package cn.icast.nio.c4;

import sun.java2d.pipe.SpanIterator;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class WriteServer {
    public static void main(String[] args) throws IOException {
        //建立服务器
        ServerSocketChannel ssc=ServerSocketChannel.open();
        // 开启非阻塞模式
        ssc.configureBlocking(false);
        //创建Selector来管理多个channel
        Selector selector = Selector.open();
        //添加注册事件
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        //绑定端口
        ssc.bind(new InetSocketAddress(8080));

        while (true){
            //有事件发生时，才会继续向下运行
            selector.select();

            // 拿到所有发生的事件，是在SelectionKey集合里
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            //进行遍历
            while (iterator.hasNext()) {// 是否有更多的元素
                // key是每一个元素事件
                SelectionKey key = iterator.next();
                // 处理过的事件的key要及时移除
                iterator.remove();
                if (key.isAcceptable()) {
                    //接收数据
                    SocketChannel sc = ssc.accept();
                    //阻塞取消
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, 0, null);
                    sckey.interestOps(SelectionKey.OP_READ);

                    // 1.向客户端大量数据
                    StringBuilder sb=new StringBuilder();
                    for (int i = 0; i < 7000000; i++) {
                        sb.append("a");

                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());

                        //2.返回值代表实际写入的大小
                    int write = sc.write(buffer);
                    System.out.println(write);

                    //3.判断是否有剩余内容
                    if (buffer.hasRemaining()) {
                     //4.关注可写事件 1         4
                        sckey.interestOps(sckey.interestOps()+SelectionKey.OP_WRITE);
                         // 5.把未写完的数据挂到sckey
                        sckey.attach(buffer);
                        }
                  }else if(key.isWritable()){
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    //6. 清理
                    if(!buffer.hasRemaining()){
                        key.attach(null);//需要清除buffer
                        //不需关注可写事件
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);
                       // System.out.println(333>>2);
                    }
                }
            }


        }
    }
}
